<?php
session_start();

// 修正 fun.ajax.php 的路径，因为它在上一级目录
// 同时，config.php 的路径也需要相对于项目根目录
$funAjaxPath = dirname(__DIR__) . '/fun.ajax.php';

// 确保 fun.ajax.php 存在并引入，它会负责加载 config.php
if (file_exists($funAjaxPath)) {
    include_once $funAjaxPath;
} else {
    die('错误：核心功能文件 fun.ajax.php 未找到。');
}

// $conf 和 $Data 变量现在应该由 fun.ajax.php 加载后可用

$is_token_set = isset($conf['token']) && !empty($conf['token']);
$message = $_SESSION['message'] ?? '';
unset($_SESSION['message']);

if (isset($_SESSION['ADMINTOKEN']) && $_SESSION['ADMINTOKEN'] == $conf['token']) {
    header('Location: dashboard.php');
    exit;
}

?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员登录 - 极简导航网</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-blue: #2563eb;
            --primary-blue-dark: #1d4ed8;
            --primary-blue-light: #3b82f6;
            --secondary-blue: #eff6ff;
            --accent-blue: #dbeafe;
            --white: #ffffff;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-300: #cbd5e1;
            --gray-400: #94a3b8;
            --gray-500: #64748b;
            --gray-600: #475569;
            --gray-700: #334155;
            --gray-800: #1e293b;
            --gray-900: #0f172a;
            --border-radius: 8px;
            --border-radius-lg: 12px;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
            --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }

        * {
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            background: linear-gradient(135deg, var(--secondary-blue) 0%, var(--accent-blue) 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            margin: 0;
            padding: 20px;
            color: var(--gray-800);
        }

        .login-container {
            background: var(--white);
            padding: 40px;
            border-radius: var(--border-radius-lg);
            box-shadow: var(--shadow-xl);
            width: 100%;
            max-width: 420px;
            text-align: center;
            border: 1px solid var(--gray-200);
        }

        .login-container h1 {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 12px;
            color: var(--gray-900);
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-blue-light) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .login-container p {
            font-size: 0.95rem;
            color: var(--gray-600);
            margin-bottom: 32px;
            line-height: 1.5;
        }

        .form-group {
            margin-bottom: 24px;
            text-align: left;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--gray-700);
            font-size: 0.9rem;
        }

        .form-group input[type="password"],
        .form-group input[type="text"] {
            width: 100%;
            padding: 14px 16px;
            border: 2px solid var(--gray-200);
            border-radius: var(--border-radius);
            font-size: 1rem;
            transition: all 0.2s ease;
            background: var(--white);
            color: var(--gray-800);
        }

        .form-group input[type="password"]:focus,
        .form-group input[type="text"]:focus {
            border-color: var(--primary-blue);
            outline: none;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            background: var(--gray-50);
        }

        .btn {
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--primary-blue-light) 100%);
            color: var(--white);
            padding: 14px 24px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            width: 100%;
            box-shadow: var(--shadow);
            position: relative;
            overflow: hidden;
        }

        .btn:hover {
            background: linear-gradient(135deg, var(--primary-blue-dark) 0%, var(--primary-blue) 100%);
            box-shadow: var(--shadow-lg);
            transform: translateY(-1px);
        }

        .btn:active {
            transform: translateY(0);
            box-shadow: var(--shadow);
        }

        .btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            pointer-events: none;
        }

        .btn-loading {
            position: relative;
            color: transparent;
        }

        .btn-loading::after {
            content: '';
            position: absolute;
            width: 20px;
            height: 20px;
            top: 50%;
            left: 50%;
            margin-left: -10px;
            margin-top: -10px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: btn-spin 0.6s linear infinite;
        }

        @keyframes btn-spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* Ant Design 风格消息提示 */
        .ant-message {
            position: fixed;
            top: 24px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1100;
            pointer-events: none;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 8px;
        }

        .ant-message-notice {
            background: var(--white);
            border-radius: 8px;
            box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            padding: 10px 16px;
            font-size: 14px;
            line-height: 1.5715;
            pointer-events: auto;
            position: relative;
            opacity: 0;
            transform: translateY(-100%);
            transition: all 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86);
            max-width: 90vw;
            word-break: break-word;
        }

        .ant-message-notice.show {
            opacity: 1;
            transform: translateY(0);
        }

        .ant-message-notice.hide {
            opacity: 0;
            transform: translateY(-100%);
            margin-top: -50px;
        }

        .ant-message-icon {
            margin-right: 8px;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .ant-message-content {
            flex: 1;
        }

        .ant-message-close {
            margin-left: 12px;
            cursor: pointer;
            color: rgba(0, 0, 0, 0.45);
            font-size: 12px;
            transition: color 0.3s;
            display: flex;
            align-items: center;
        }

        .ant-message-close:hover {
            color: rgba(0, 0, 0, 0.75);
        }

        /* 不同类型的消息样式 */
        .ant-message-success .ant-message-icon {
            color: #52c41a;
        }

        .ant-message-error .ant-message-icon {
            color: #ff4d4f;
        }

        .ant-message-warning .ant-message-icon {
            color: #faad14;
        }

        .ant-message-info .ant-message-icon {
            color: #1890ff;
        }

        .ant-message-loading .ant-message-icon {
            color: #1890ff;
        }

        /* 加载动画 */
        .ant-message-loading .ant-message-icon {
            animation: ant-spin 1s infinite linear;
        }

        @keyframes ant-spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 移动端优化 */
        @media (max-width: 768px) {
            body {
                padding: 16px;
                background: linear-gradient(135deg, var(--secondary-blue) 0%, var(--accent-blue) 100%);
                background-attachment: fixed;
            }

            .login-container {
                padding: 32px 24px;
                max-width: 100%;
                border-radius: 10px;
                box-shadow: var(--shadow-lg);
            }

            .login-container h1 {
                font-size: 1.8rem;
                margin-bottom: 10px;
            }

            .login-container p {
                font-size: 0.9rem;
                margin-bottom: 28px;
                line-height: 1.4;
            }

            .form-group {
                margin-bottom: 20px;
            }

            .form-group label {
                font-size: 0.85rem;
                margin-bottom: 6px;
            }

            .form-group input[type="password"],
            .form-group input[type="text"] {
                padding: 12px 14px;
                font-size: 0.95rem;
                border-radius: 6px;
            }

            .btn {
                padding: 12px 20px;
                font-size: 0.95rem;
                border-radius: 6px;
            }

            .message {
                padding: 14px 16px;
                margin-bottom: 20px;
                font-size: 0.85rem;
                border-radius: 6px;
            }
        }

        /* 小屏手机优化 (≤480px) */
        @media (max-width: 480px) {
            body {
                padding: 12px;
                align-items: flex-start;
                padding-top: 20vh; /* 在小屏幕上稍微向上移动表单 */
            }

            .login-container {
                padding: 28px 20px;
                border-radius: 8px;
                box-shadow: var(--shadow);
            }

            .login-container h1 {
                font-size: 1.6rem;
                margin-bottom: 8px;
            }

            .login-container p {
                font-size: 0.85rem;
                margin-bottom: 24px;
            }

            .form-group {
                margin-bottom: 18px;
            }

            .form-group label {
                font-size: 0.8rem;
                margin-bottom: 5px;
            }

            .form-group input[type="password"],
            .form-group input[type="text"] {
                padding: 11px 12px;
                font-size: 0.9rem;
                border-radius: 5px;
            }

            .btn {
                padding: 11px 18px;
                font-size: 0.9rem;
                border-radius: 5px;
            }

            .message {
                padding: 12px 14px;
                margin-bottom: 18px;
                font-size: 0.8rem;
                border-radius: 5px;
            }
        }

        /* 超小屏设备优化 (≤360px) */
        @media (max-width: 360px) {
            body {
                padding: 8px;
                padding-top: 15vh;
            }

            .login-container {
                padding: 24px 16px;
            }

            .login-container h1 {
                font-size: 1.4rem;
            }

            .login-container p {
                font-size: 0.8rem;
                margin-bottom: 20px;
            }

            .form-group {
                margin-bottom: 16px;
            }

            .form-group input[type="password"],
            .form-group input[type="text"] {
                padding: 10px 11px;
                font-size: 0.85rem;
            }

            .btn {
                padding: 10px 16px;
                font-size: 0.85rem;
            }
        }

        /* 横屏模式优化 */
        @media (max-width: 768px) and (orientation: landscape) {
            body {
                padding-top: 5vh;
                align-items: flex-start;
            }

            .login-container {
                margin-top: 20px;
                margin-bottom: 20px;
            }

            .login-container h1 {
                font-size: 1.6rem;
                margin-bottom: 6px;
            }

            .login-container p {
                font-size: 0.85rem;
                margin-bottom: 20px;
            }

            .form-group {
                margin-bottom: 16px;
            }

            .message {
                margin-bottom: 16px;
            }
        }
    </style>
</head>

<body>
    <!-- Ant Design 风格消息提示容器 -->
    <div class="ant-message" id="ant-message"></div>
    
    <div class="login-container">
        <h1>管理员<?php echo $is_token_set ? '登录' : '设置密钥'; ?></h1>
        <p><?php echo $is_token_set ? '请输入您的管理密钥进行登录。' : '系统检测到您尚未设置管理密钥，请设置一个新密钥。'; ?></p>


        <form action="main.php" method="POST">
            <?php if ($is_token_set): ?>
                <input type="hidden" name="act" value="login">
                <div class="form-group">
                    <label for="token">管理密钥</label>
                    <input type="password" id="token" name="token" required>
                </div>
                <button type="submit" class="btn">登录</button>
            <?php else: ?>
                <input type="hidden" name="act" value="setLoginToken">
                <div class="form-group">
                    <label for="new_token">设置新密钥</label>
                    <input type="password" id="new_token" name="token" required>
                </div>
                <div class="form-group">
                    <label for="confirm_token">确认新密钥</label>
                    <input type="password" id="confirm_token" name="confirm_token" required>
                </div>
                <button type="submit" class="btn">设置密钥</button>
            <?php endif; ?>
        </form>
    </div>

    <script>
        // Ant Design 风格消息提示系统
        const AntMessage = {
            container: null,
            
            init() {
                this.container = document.getElementById('ant-message');
                if (!this.container) {
                    this.container = document.createElement('div');
                    this.container.className = 'ant-message';
                    this.container.id = 'ant-message';
                    document.body.appendChild(this.container);
                }
            },
            
            show(content, type = 'info', duration = 3) {
                if (!this.container) this.init();
                
                const icons = {
                    success: 'fas fa-check-circle',
                    error: 'fas fa-times-circle',
                    warning: 'fas fa-exclamation-triangle',
                    info: 'fas fa-info-circle',
                    loading: 'fas fa-spinner'
                };
                
                const notice = document.createElement('div');
                notice.className = `ant-message-notice ant-message-${type}`;
                
                notice.innerHTML = `
                    <span class="ant-message-icon">
                        <i class="${icons[type] || icons.info}"></i>
                    </span>
                    <span class="ant-message-content">${content}</span>
                    <span class="ant-message-close">
                        <i class="fas fa-times"></i>
                    </span>
                `;
                
                // 添加关闭按钮事件
                const closeBtn = notice.querySelector('.ant-message-close');
                closeBtn.addEventListener('click', () => {
                    this.hide(notice);
                });
                
                // 添加到容器
                this.container.appendChild(notice);
                
                // 显示动画
                setTimeout(() => {
                    notice.classList.add('show');
                }, 10);
                
                // 自动隐藏
                if (duration > 0) {
                    setTimeout(() => {
                        this.hide(notice);
                    }, duration * 1000);
                }
                
                return notice;
            },
            
            hide(notice) {
                if (!notice || !notice.parentNode) return;
                
                notice.classList.add('hide');
                setTimeout(() => {
                    if (notice.parentNode) {
                        notice.parentNode.removeChild(notice);
                    }
                }, 300);
            },
            
            success(content, duration = 3) {
                return this.show(content, 'success', duration);
            },
            
            error(content, duration = 4) {
                return this.show(content, 'error', duration);
            },
            
            warning(content, duration = 3) {
                return this.show(content, 'warning', duration);
            },
            
            info(content, duration = 3) {
                return this.show(content, 'info', duration);
            },
            
            loading(content, duration = 0) {
                return this.show(content, 'loading', duration);
            }
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化消息系统
            AntMessage.init();
            
            // 显示PHP消息（如果有）
            <?php if ($message): ?>
            const messageType = '<?php echo strpos(strtolower($message), "成功") !== false ? "success" : "error"; ?>';
            const messageContent = <?php echo json_encode($message); ?>;
            AntMessage[messageType](messageContent);
            <?php endif; ?>

            // 处理表单提交
            const loginForm = document.querySelector('form');
            const submitBtn = loginForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.textContent;

            loginForm.addEventListener('submit', function(e) {
                // 验证表单
                const inputs = loginForm.querySelectorAll('input[required]');
                let isValid = true;
                
                inputs.forEach(input => {
                    if (!input.value.trim()) {
                        isValid = false;
                    }
                });

                if (!isValid) {
                    return; // 让浏览器的默认验证处理
                }

                <?php if (!$is_token_set): ?>
                // 如果是设置密钥，检查两次输入是否一致
                const newToken = document.getElementById('new_token').value;
                const confirmToken = document.getElementById('confirm_token').value;
                
                if (newToken !== confirmToken) {
                    e.preventDefault();
                    AntMessage.error('两次输入的密钥不一致，请重新输入');
                    return;
                }
                <?php endif; ?>

                // 显示loading状态
                submitBtn.disabled = true;
                submitBtn.classList.add('btn-loading');
                submitBtn.setAttribute('data-original-text', originalBtnText);
                
                // 显示loading消息
                AntMessage.loading('<?php echo $is_token_set ? "正在登录..." : "正在设置密钥..."; ?>', 0);
            });

            // 监听页面可见性变化，如果用户切换回来且表单还在loading状态，恢复按钮
            document.addEventListener('visibilitychange', function() {
                if (!document.hidden && submitBtn.disabled) {
                    // 如果5秒后还没有跳转，恢复按钮状态
                    setTimeout(function() {
                        if (submitBtn.disabled) {
                            submitBtn.disabled = false;
                            submitBtn.classList.remove('btn-loading');
                            AntMessage.error('操作超时，请重试');
                        }
                    }, 5000);
                }
            });
        });
    </script>
</body>

</html>